import { computed, Ref, ref } from 'vue';
import { ButtonProps, DropdownProps, DropdownButton, Menu, MenuItem, Empty } from 'ant-design-vue';
import { DeleteOutlined } from '@ant-design/icons-vue';
import { isFunction } from '/@/utils/is';

type DropdownOptions = DropdownOption[];
type DropdownOption = {
  label: string;
  value: string;
};

type ButtonDropdownProps = DropdownProps &
  ButtonProps & {
    value: Ref<string>;
    options: DropdownOptions | (() => DropdownOptions) | (() => Promise<DropdownOptions>);
    buttonText: string;
    onItem?: (val: any) => void;
    onItemDel?: (val: any) => void;
  };

export function useButtonDropdown(props: ButtonDropdownProps) {
  const value = computed({
    set: (val) => {
      props.value.value = val[0];
    },
    get: () => [props.value.value],
  });

  const options = ref<DropdownOptions>([]);

  function initOptions() {
    if (isFunction(props.options)) {
      const op = props.options();
      // @ts-ignore
      if (op.catch || op.then) {
        // @ts-ignore
        op.then((res) => {
          options.value = res;
        });
      } else {
        // @ts-ignore
        options.value = op;
      }
    } else {
      options.value = props.options;
    }
  }

  initOptions();

  function onMenuItem(val) {
    props.onItem && props.onItem(val.key);
  }

  function onMenuItemDel(val, index) {
    options.value.splice(index, 1);
    props.onItemDel && props.onItemDel(val);
  }

  function addOption(key: string, name: string) {
    options.value.push({ label: name, value: key });
  }

  const MenuItems = () => (
    <Menu size={props.size} onClick={onMenuItem} vModel={[value.value, 'selectedKeys']}>
      {options.value.length > 0 ? (
        options.value.map((op, index) => (
          <div class={'dc-flex dc-flex-center dc-p-5px'}>
            <MenuItem key={op.value}>
              <span
                class={'dc-inline-block dc-text-hidden-1 dc-max-width-200px dc-min-width-100px'}
              >
                {op.label}{' '}
              </span>
            </MenuItem>
            <div
              class={'dc-m-x-10px dc-cursor-pointer'}
              onClick={() => onMenuItemDel(op.value, index)}
            >
              <DeleteOutlined></DeleteOutlined>
            </div>
          </div>
        ))
      ) : (
        <Empty description={'暂无保存的条件'}></Empty>
      )}
    </Menu>
  );
  const ButtonDropdown = () => (
    <DropdownButton placement={'bottomRight'} {...props}>
      {{
        default: () => props.buttonText,
        overlay: () => <MenuItems></MenuItems>,
      }}
    </DropdownButton>
  );

  return {
    ButtonDropdown,
    value,
    addOption,
  };
}
